package OrderService

import (
	"context"
	"gdshop-font-api-go/app/request/OrderReq"
	"gdshop-font-api-go/library/response"
	toolsDb "gdshop-font-api-go/library/tools/db"
	"github.com/gogf/gf/container/gset"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	_ "github.com/hprose/hprose-golang/rpc/fasthttp"
)

// Logistics 物流信息
func Logistics(ctx context.Context, parames *OrderReq.Logistics) *response.JsonResponse {
	oModel, err := GetOrderModel(ctx, parames.OrderId)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	if oModel == nil {
		return response.FailByRequestMessage(nil, "找不到订单")
	}

	if oModel.MemberId != int(parames.MemberId) {
		return response.FailByRequestMessage(nil, "请勿操作别人的订单")
	}
	var resAll gdb.Result

	resAll, err = toolsDb.GetUnSafaTable(ctx, "order_express").As("oe").Fields(
		"os.goods_cover,os.goods_option_thumb,oe.express_com,oe.express,oe.express_sn",
	).LeftJoin("order_sub os", "oe.order_sub_id = os.id").Where(
		"oe.delete_at < 1 AND (os.order_id = ? OR oe.order_id = ?)", parames.OrderId,
		parames.OrderId,
	).All()

	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	sns := gset.StrSet{}
	resList := g.List{}
	// 循环读取快递信息
	for _, item := range resAll {
		tmpSn := gconv.String(item["express_sn"])

		if sns.ContainsI(tmpSn) {
			continue
		}

		tmp, err := GetExpressBySn(tmpSn)
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		resList = append(resList, g.Map{
			"express_com":  item["express_com"],
			"express_sn":   tmpSn,
			"goods_photos": getGoodsPhotos(tmpSn, resAll),
			"list":         tmp,
		})

		sns.Add(tmpSn)
	}

	return response.SuccessByRequestMessageData(nil, "成功", g.Map{
		"order_no":       oModel.OrderNo,
		"logistics_list": resList,
		"is_split":       oModel.IsSplit,
		"photo_base_url": g.Cfg().GetString("site.PhotoUrlProfix"),
	})
}

func getGoodsPhotos(expressSn string, l gdb.Result) []string {
	tmp := []string{}
	for _, item := range l {
		tmpSn := gconv.String(item["express_sn"])
		if tmpSn == expressSn {
			if gconv.String(item["goods_option_thumb"]) != "" {
				tmp = append(tmp, gconv.String(item["goods_option_thumb"]))
			}
			if gconv.String(item["goods_cover"]) != "" {
				tmp = append(tmp, gconv.String(item["goods_cover"]))
			}
		}
	}

	return tmp
}
